import React, { useState, useEffect } from 'react';
import { Card, List, Input, Button, Typography, Spin, Empty, Tag, Space, Pagination } from 'antd';
import { SearchOutlined, FileTextOutlined, EyeOutlined } from '@ant-design/icons';
import { getAllHelpDocs, searchHelpDocs, getHelpDocById, type HelpDocument } from '@/services/help-docs/api';
import './index.less';

const { Title, Paragraph, Text } = Typography;
const { Search } = Input;

const HelpDocsPage: React.FC = () => {
  const [documents, setDocuments] = useState<HelpDocument[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedDoc, setSelectedDoc] = useState<HelpDocument | null>(null);
  const [searchResults, setSearchResults] = useState<HelpDocument[]>([]);
  const [searchLoading, setSearchLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [pageSize] = useState(20);

  // 加载所有文档
  useEffect(() => {
    loadDocuments();
  }, []);

  const loadDocuments = async () => {
    setLoading(true);
    try {
      const response = await getAllHelpDocs();
      if (response.success && Array.isArray(response.data)) {
        setDocuments(response.data);
      }
    } catch (error) {
      console.error('加载文档失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 搜索文档
  const handleSearch = async (keyword: string, page: number = 1) => {
    if (!keyword.trim()) {
      setSearchResults([]);
      setSearchKeyword('');
      return;
    }

    setSearchLoading(true);
    setSearchKeyword(keyword);
    setCurrentPage(page);

    try {
      const response = await searchHelpDocs(keyword, page, pageSize);
      if (response.success) {
        setSearchResults(response.data);
        setTotal(response.total);
      }
    } catch (error) {
      console.error('搜索失败:', error);
    } finally {
      setSearchLoading(false);
    }
  };

  // 查看文档详情
  const handleViewDoc = async (doc: HelpDocument) => {
    try {
      const response = await getHelpDocById(doc.id);
      if (response.success && !Array.isArray(response.data)) {
        setSelectedDoc(response.data);
      }
    } catch (error) {
      console.error('获取文档详情失败:', error);
    }
  };

  // 渲染文档内容（HTML）
  const renderContent = (content: string) => {
    return <div dangerouslySetInnerHTML={{ __html: content }} />;
  };

  // 显示的数据列表（搜索时显示搜索结果，否则显示所有文档）
  const displayList = searchKeyword ? searchResults : documents;
  const displayLoading = searchKeyword ? searchLoading : loading;

  return (
    <div className="help-docs-page">
      <Card>
        <Title level={2}>
          <FileTextOutlined /> 帮助文档
        </Title>
        <Paragraph>查看和管理帮助文档</Paragraph>

        {/* 搜索框 */}
        <div className="search-section">
          <Search
            placeholder="搜索帮助文档..."
            allowClear
            enterButton={<SearchOutlined />}
            size="large"
            onSearch={(value) => handleSearch(value, 1)}
            style={{ marginBottom: 16 }}
          />
        </div>

        <div className="content-section">
          {/* 文档列表 */}
          <div className="doc-list-section">
            <Card title={searchKeyword ? `搜索结果 (${total})` : `全部文档 (${documents.length})`}>
              <Spin spinning={displayLoading}>
                {displayList.length > 0 ? (
                  <>
                    <List
                      dataSource={displayList}
                      renderItem={(doc) => (
                        <List.Item
                          key={doc.id}
                          onClick={() => handleViewDoc(doc)}
                          style={{
                            cursor: 'pointer',
                            padding: '12px',
                            borderBottom: '1px solid #f0f0f0',
                            backgroundColor: selectedDoc?.id === doc.id ? '#e6f7ff' : 'transparent',
                          }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = '#f5f5f5';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor =
                              selectedDoc?.id === doc.id ? '#e6f7ff' : 'transparent';
                          }}
                        >
                          <List.Item.Meta
                            title={
                              <Space>
                                <Text strong>{doc.title}</Text>
                                {doc.category && <Tag color="blue">{doc.category}</Tag>}
                              </Space>
                            }
                            description={
                              <div>
                                {doc.summary && (
                                  <Paragraph ellipsis={{ rows: 2 }} style={{ marginBottom: 8 }}>
                                    {doc.summary}
                                  </Paragraph>
                                )}
                                <Space>
                                  <Text type="secondary">
                                    <EyeOutlined /> {doc.viewCount}
                                  </Text>
                                  <Text type="secondary">{new Date(doc.createdAt).toLocaleDateString()}</Text>
                                </Space>
                              </div>
                            }
                          />
                        </List.Item>
                      )}
                    />
                    {searchKeyword && total > pageSize && (
                      <div style={{ marginTop: 16, textAlign: 'right' }}>
                        <Pagination
                          current={currentPage}
                          total={total}
                          pageSize={pageSize}
                          onChange={(page) => handleSearch(searchKeyword, page)}
                        />
                      </div>
                    )}
                  </>
                ) : (
                  <Empty description="暂无文档" />
                )}
              </Spin>
            </Card>
          </div>

          {/* 文档详情 */}
          <div className="doc-detail-section">
            <Card title={selectedDoc ? selectedDoc.title : '请选择文档'} extra={<Tag>浏览量: {selectedDoc?.viewCount || 0}</Tag>}>
              {selectedDoc ? (
                <div className="doc-content">
                  {selectedDoc.summary && (
                    <Paragraph type="secondary" style={{ marginBottom: 16 }}>
                      {selectedDoc.summary}
                    </Paragraph>
                  )}
                  <div className="doc-html-content">{renderContent(selectedDoc.content)}</div>
                  <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid #f0f0f0' }}>
                    <Space>
                      <Text type="secondary">来源: </Text>
                      <a href={selectedDoc.url} target="_blank" rel="noopener noreferrer">
                        {selectedDoc.url}
                      </a>
                    </Space>
                  </div>
                </div>
              ) : (
                <Empty description="请从左侧列表选择文档查看详情" />
              )}
            </Card>
          </div>
        </div>
      </Card>
    </div>
  );
};

export default HelpDocsPage;

